package xyz.quanguanjia.masterboy.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import xyz.quanguanjia.masterboy.MBDApplication;
import xyz.quanguanjia.masterboy.groupDetail.MBDGroupDetailActivity;
import xyz.quanguanjia.masterboy.MBDGroupDetailModel;
import xyz.quanguanjia.masterboy.MBDHttpClient;
import xyz.quanguanjia.masterboy.MBDModelResponse;
import xyz.quanguanjia.masterboy.MBDToolbarUtils;
import xyz.quanguanjia.masterboy.R;
import xyz.quanguanjia.masterboy.ServiceType;
import xyz.quanguanjia.masterboy.adapter.SearchGroupAdapter;
import xyz.quanguanjia.masterboy.decoration.HomeItemDecoration;
import xyz.quanguanjia.masterboy.util.StringUtils;

public class MBDGroupActivity extends AppCompatActivity implements HomeItemDecoration.HomeItemClickListener {
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView recyclerView;

    private int page = 1;

    private String searchQuery;

    private SearchGroupAdapter adapter;

    private List<MBDGroupDetailModel> mbdGroupDetailModelList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_group);
        mbdGroupDetailModelList = new ArrayList<>();
        smartRefreshLayout = findViewById(R.id.refresh_layout);
        EditText toolbarSearchEt = findViewById(R.id.toolbar_search_et);
        recyclerView = findViewById(R.id.recyclerView);

        toolbarSearchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_ENTER == event.getKeyCode())) {
                    // 在这里执行搜索操作
                    searchQuery = toolbarSearchEt.getText().toString();
                    getData("Refresh");
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(toolbarSearchEt.getWindowToken(), 0);
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                    return true; // 表示已经处理了这个动作
                }
                return false; // 表示没有处理这个动作
            }
        });


        Toolbar toolbar = findViewById(R.id.toolbar);

        MBDToolbarUtils.backButtonClicked(toolbar, new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
        //下拉刷新上拉加载更多
        smartRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        smartRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            getData("Refresh");
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> getData("load"));
        LinearLayoutManager layoutManager = new LinearLayoutManager(MBDApplication.getContext());
        recyclerView.setLayoutManager(layoutManager);
        HomeItemDecoration hi = new HomeItemDecoration(this);
        recyclerView.addItemDecoration(hi);
        recyclerView.addItemDecoration(new DividerItemDecoration(MBDApplication.getContext(), LinearLayoutManager.VERTICAL));
    }

    @Override
    public void onItemClick(int position) {
        Intent intent = new Intent(this, MBDGroupDetailActivity.class);
        intent.putExtra("detail", this.mbdGroupDetailModelList.get(position));
        startActivity(intent);
        finish();
    }

    public void getData(String info) {
        if (StringUtils.isNull(searchQuery)) {
            smartRefreshLayout.finishRefresh(true);
            smartRefreshLayout.finishLoadMore(true);
            return;
        }
        if (info.equals("Refresh")) {
            mbdGroupDetailModelList.clear();
            page = 1;
        } else {
            ++page;
        }
        this.doRequest(new HomeFragment.CallBack() {
            @Override
            public void completion(List<MBDGroupDetailModel> details, boolean isShowLoad) {
                if (info.equals("Refresh")) {
                    smartRefreshLayout.finishRefresh(true);
                    if (null != details && details.size() > 0) {
                        mbdGroupDetailModelList.addAll(details);
                        if (null == adapter) {
                            adapter = new SearchGroupAdapter(mbdGroupDetailModelList);
                            recyclerView.setAdapter(adapter);
                        }
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    smartRefreshLayout.finishLoadMore(true);
                    if (null != details && details.size() > 0) {
                        mbdGroupDetailModelList.addAll(details);
                        adapter.notifyItemChanged(mbdGroupDetailModelList.size() - details.size() + 1);
                    }
                }
                smartRefreshLayout.setNoMoreData(isShowLoad);
            }
        });
    }

    private void doRequest(HomeFragment.CallBack callBack) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("pageNum", this.page + "");
        params.put("keyword", searchQuery);
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_HOME_LIST, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    ArrayList list = (ArrayList) response.data;
                    ArrayList resultArrayList = new ArrayList<MBDGroupDetailModel>();
                    for (int i = 0; i < list.size(); i++) {
                        LinkedTreeMap<String, Object> linkedTreeMap = (LinkedTreeMap<String, Object>) list.get(i);
                        Gson gson = new Gson();
                        String jsonString = gson.toJson(linkedTreeMap);
                        MBDGroupDetailModel detail = gson.fromJson(jsonString, MBDGroupDetailModel.class);
                        resultArrayList.add(detail);
                    }
                    callBack.completion(resultArrayList, response.total == list.size() + mbdGroupDetailModelList.size());
                }
            }
        });
    }
}
